package com.lailai.utils;

import com.lailai.entity.Route;
import com.lailai.entity.RouteConfig;
import com.lailai.entity.vo.RouteVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @Author lgr
 * @Date 2025/7/11
 * @Wechat a983105834
 * @Email 983105834@qq.com
 * @Copyright <a href="www.lailai.ink">lailai个人空间</a>
 */
public class RouteTreeUtil {
    // 创建日志记录器
    private static final Logger logger = LoggerFactory.getLogger(RouteTreeUtil.class);


    /**
     * 将 RouteVO 转换为 Route 实体类
     */
    public static Route convertToEntity(RouteVO vo) {
        Route route = new Route();
        route.setId(vo.getId());
        route.setParentId(vo.getMeta().getParentId());
        route.setName(vo.getName());
        route.setPath(vo.getPath());
        route.setComponentPath(vo.getComponentPath());
        route.setRedirect(vo.getRedirect() != null ? vo.getRedirect().toString() : null);
        route.setProps(vo.getMeta().getProps());
        route.setLevel(vo.getMeta().getLevel());
        route.setSort(vo.getMeta().getSort());
        route.setStatus(vo.getMeta().getStatus());
        return route;
    }

    /**
     * 将 Route 实体类转换为 RouteVO
     */
    public static RouteVO convertToVO(Route route) {
        RouteVO vo = new RouteVO();
        // 确保 meta 被初始化
        if (vo.getMeta() == null) {
            vo.setMeta(new RouteVO.Meta());
        }

        vo.setId(route.getId());
        vo.getMeta().setParentId(route.getParentId());
        vo.setName(route.getName());
        vo.setPath(route.getPath());
        vo.setComponentPath(route.getComponentPath());
        vo.setRedirect(route.getRedirect()); // 直接从route获取
        vo.getMeta().setProps(route.getProps());
        vo.getMeta().setLevel(route.getLevel());
        vo.getMeta().setSort(route.getSort());
        vo.getMeta().setStatus(route.getStatus());
        vo.getMeta().setCreateTime(route.getCreateTime());
        vo.getMeta().setUpdateTime(route.getUpdateTime());

        // 构建 Meta 信息
        RouteVO.Meta meta = new RouteVO.Meta();
        RouteConfig routeConfig = route.getRoutesConfig();

        if (routeConfig != null) {
            meta.setTitle(routeConfig.getTitle());
            meta.setIcon(routeConfig.getIcon());
            meta.setNoCache(routeConfig.getNoCache());
            meta.setAffix(routeConfig.getAffix());
            meta.setBreadcrumb(routeConfig.getBreadcrumb());
            meta.setHidden(routeConfig.getHidden());
            meta.setRoles(routeConfig.getRoles());
            meta.setRequiresAuth(routeConfig.getRequiresAuth());
            meta.setKeepAlive(routeConfig.getKeepAlive());
            meta.setPermissions(routeConfig.getPermissions());
            meta.setBeforeEnter(routeConfig.getBeforeEnter()); // 添加这个字段
        } else {
            logger.warn("路由ID={} 没有配置信息", route.getId());
        }

        vo.setMeta(meta);
        return vo;
    }

    /**
     * 将扁平的路由列表转换为树形结构
     */
    public static List<RouteVO> buildRouteTree(List<RouteVO> routes) {
        // 1. 创建一个Map，以路由ID为键，路由对象为值，便于快速查找
        Map<Long, RouteVO> routeMap = routes.stream()
                .collect(Collectors.toMap(RouteVO::getId, Function.identity()));

        // 2. 创建结果列表
        List<RouteVO> tree = new ArrayList<>();

        // 3. 遍历所有路由
        for (RouteVO route : routes) {
            // 4. 如果parentId为null或者为0，说明是根节点，直接添加到结果列表
            if (route.getMeta().getParentId() == null || route.getMeta().getParentId() == 0) {
                tree.add(route);
            } else {
                // 5. 否则，通过parentId查找父节点
                RouteVO parent = routeMap.get(route.getMeta().getParentId());
                if (parent != null) {
                    // 6. 如果父节点存在，将当前路由添加到父节点的children列表中
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(route);
                } else {
                    logger.warn("未找到父节点，ParentId={}", route.getMeta().getParentId());
                }
            }
        }
        return tree;
    }

    /**
     * 将树形结构的路由列表转换为扁平结构
     */
    public static List<RouteVO> flattenRouteTree(List<RouteVO> routes) {
        List<RouteVO> result = new ArrayList<>();
        for (RouteVO route : routes) {
            result.add(route);
            if (route.getChildren() != null && !route.getChildren().isEmpty()) {
                result.addAll(flattenRouteTree(route.getChildren()));
            }
        }
        return result;
    }
}
